﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.PostModel;
using WebApi.Models;
using WebApi.Class;
using Yd.Domain.DAL;
using Yd.BLL;
using System.Data;
using System.Data.SqlClient;
using Yd.Model;
using System.Text;
namespace WebApi.Controllers
{
    public class UsersController : ApiController
    {
        //
        // GET: /Users/
        public CommDAL commdal = new CommDAL();
        // Post 用户登录 api/user/login
        /// <returns>登录成功返回userinfo  -1异常 -4 参数错误</returns>
        public object UserLogin([FromBody]PostLogin post)
        {
            ModelBase mbase = new ModelBase();
            if (StringUtils.getIsEmpty(post.code))
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            if (commdal.g1byopenid(post.openid))
            {
                mbase.code = -1;
                mbase.message = "您已被管理员设置为黑名单!";
                return mbase;
            }
            DataSet ds;
            WechatLoginInfo login = new WechatLoginInfo();
            login.code = post.code;
            WeChatAppDecrypt chatapp = new WeChatAppDecrypt("wxd69325a1c32016de", "675905929b96ba8af650f310691b646b");
            OpenIdAndSessionKey openid = chatapp.DecodeOpenIdAndSessionKey(login);
            if (openid == null)
            {
                mbase.code = -8;
                mbase.message = ErrorCodeUtil.getCodeMessage(-8);
                return mbase;
            }
            yd_users tzuser = new yd_users();
            tzuser.openid = openid.openid;
            tzuser.session_key = openid.session_key;
            int ret = commdal.InsertUser(tzuser);
            if (ret < 0) {
                mbase.code = -1;
                mbase.message = ErrorCodeUtil.getCodeMessage(-1);
                return mbase;
            }
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@openid",openid.openid),
                new SqlParameter("@uid",ret),
            };
            ds = commdal.QueryObject("getUserInfoByOpenId", fparam);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                //commdal.SaveOrUpdateSql("update tz_user set cwcs=0 where username='" + ds.Tables[0].Rows[0]["username"].ToString().Trim().Replace("\'", "") + "'");
                //string insert = String.Format("INSERT INTO tz_login_log(uid,userName,device) VALUES({0},'{1}','{2}')", ds.Tables[0].Rows[0]["Id"].ToString(), ds.Tables[0].Rows[0]["username"].ToString().Trim(), post.device);
                //commdal.SaveOrUpdateSql(insert);
                UserInfoModel userInfo = UserInfoModel.GetUserInfo(ds.Tables[0].Rows[0]);
                if (userInfo != null)
                {
                    mbase.code = 0;
                    userInfo.isFristLogin = ret != 0 ? 1 : 0;//用户编号为0 不是第一次登陆
                    mbase.data = userInfo;
                    mbase.message = ErrorCodeUtil.getCodeMessage(0);
                }
                else
                {
                    mbase.code = -1;
                    mbase.message = ErrorCodeUtil.getCodeMessage(-1);
                }
            }
            else
            {
                mbase.code = -1;
                mbase.message = ErrorCodeUtil.getCodeMessage(-1); ;
            }
            return mbase;
        }

        // Post 獲取用戶信息 api/users/PostUserInfo
        /// <returns>成功返回0  -1异常 -4 参数错误</returns>
        public object PostUserInfo([FromBody]PostUserJine post)
        {
            ModelBase mbase = new ModelBase();
            if (post.userId == 0)
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            if (commdal.g1(post.userId))
            {
                mbase.code = -1;
                mbase.message = "您已被管理员设置为黑名单!";
                return mbase;
            }
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@openid",@""),
                new SqlParameter("@uid",post.userId)
            };
            DataSet dsuser = commdal.QueryObject("getUserInfoByOpenId", fparam);
            if (dsuser != null && dsuser.Tables[0].Rows.Count > 0)
            {
                UserInfoModel userInfo = UserInfoModel.GetUserInfo(dsuser.Tables[0].Rows[0]);
                if (userInfo != null)
                {
                    mbase.code = 0;
                    mbase.data = userInfo;
                    mbase.message = ErrorCodeUtil.getCodeMessage(0);
                }
                else
                {
                    mbase.code = -1;
                    mbase.message = ErrorCodeUtil.getCodeMessage(-1);
                }
            }
            else
            {
                mbase.code = -3;
                mbase.message = ErrorCodeUtil.getCodeMessage(-3);
            }
            return mbase;
        }

        // Post 獲取用戶信息 api/users/PostEditUser
        /// <returns>成功返回0  -1异常 -4 参数错误</returns>
        public object PostEditUser([FromBody]PostEditUserInfo post)
        {
            ModelBase mbase = new ModelBase();
            if (post.userId == 0 || (StringUtils.getIsEmpty(post.userName) && StringUtils.getIsEmpty(post.headUrl)))
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            if (commdal.g1(post.userId))
            {
                mbase.code = -1;
                mbase.message = "您已被管理员设置为黑名单!";
                return mbase;
            }
            StringBuilder sql = new StringBuilder();
            sql.Append("update yd_users set ");
            if (!StringUtils.getIsEmpty(post.userName)) {
                sql.Append(" userName='" + post.userName + "',");
            }
            if (!StringUtils.getIsEmpty(post.mobile))
            {
                sql.Append(" mobile='" + post.mobile + "',");
            }
            if (!StringUtils.getIsEmpty(post.headUrl))
            {
                sql.Append(" headUrl='" + post.headUrl + "',");
            }
            if (post.sex > 0) {
                sql.Append(" sex=" + post.sex+",");
            }
            sql.Remove(sql.Length - 1, 1);
            sql.Append(" where uid=" + post.userId);
            int _fresult = -1;
            _fresult = commdal.SaveOrUpdateSql(sql.ToString());

            if (_fresult == 0)
            {
                mbase.code = 0;
                mbase.message = "修改成功";
                return mbase;
            }
            else
            {
                mbase.code = -1;
                mbase.message = ErrorCodeUtil.getCodeMessage(-1);
            }
            return mbase;
        }

        // Post 收藏商家 api/user/login
        /// <returns>登录成功返回userinfo  -1异常 -4 参数错误</returns>
        public object InsertFavorites([FromBody]PostAddFavorites post)
        {
            ModelBase mbase = new ModelBase();
            if (post.shopId < 1 || post.userId < 1)
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@uid",post.userId),
                new SqlParameter("@shopid",post.shopId)
            };
            int _fresult = -1;
            _fresult = commdal.UpdateDataByPro("InsertFavorites", fparam);
            if (_fresult == 0)
            {
                mbase.code = 0;
                mbase.message = "收藏成功";
                return mbase;
            }
            mbase.code = _fresult;
            mbase.message = ErrorCodeUtil.getCodeMessage(_fresult);
            return mbase;
        }

        // Post 取消收藏商家 api/user/login
        /// <returns>登录成功返回userinfo  -1异常 -4 参数错误</returns>
        public object CancelFavorites([FromBody]PostAddFavorites post)
        {
            ModelBase mbase = new ModelBase();
            if (post.shopId < 1 || post.userId < 1)
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            int _fresult = -1;
            _fresult = commdal.SaveOrUpdateSql("DELETE FROM yd_favorites where uid=" + post.userId + " and shopId=" + post.shopId); ;
            if (_fresult == 0)
            {
                mbase.code = 0;
                mbase.message = "取消成功";
                return mbase;
            }
            mbase.code = _fresult;
            mbase.message = ErrorCodeUtil.getCodeMessage(_fresult);
            return mbase;
        }

        /// Post 獲取收藏列表 
        /// <returns>成功返回0  -1异常 -4 参数错误</returns>
        public object FavoritesList([FromBody]PostFavoritesList post)
        {
            ModelBase mbase = new ModelBase();
            if (post.userId == 0)
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            string pagewhere = " uid=" + post.userId;
            if (post.pageSize == 0)
            {
                post.pageSize = 10;
            }
            DataSet newlist = commdal.QueryObjectAllSql("declare @t int Execute Proce_Sql_PageChange 'view_favorites',' * ',' fid desc','" + pagewhere + "'," + post.pageSize + "," + post.pageIndex + ",@t output");
            if (newlist != null)
            {
                mbase.code = 0;
                mbase.data = newlist.Tables[0];
                mbase.message = "获取成功";
            }
            else
            {
                mbase.code = -1;
                mbase.message = ErrorCodeUtil.getCodeMessage(-1);
            }
            return mbase;
        }

        public object historyList([FromBody]PostFavoritesList post)
        {
            ModelBase mbase = new ModelBase();
            if (post.userId == 0)
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            string pagewhere = " uid=" + post.userId;
            if (post.pageSize == 0)
            {
                post.pageSize = 10;
            }
            DataSet newlist = commdal.QueryObjectAllSql("declare @t int Execute Proce_Sql_PageChange 'view_shophistory',' * ',' updateTime desc','" + pagewhere + "'," + post.pageSize + "," + post.pageIndex + ",@t output");
            if (newlist != null)
            {
                mbase.code = 0;
                mbase.data = newlist.Tables[0];
                mbase.message = "获取成功";
            }
            else
            {
                mbase.code = -1;
                mbase.message = ErrorCodeUtil.getCodeMessage(-1);
            }
            return mbase;
        }

        // Post 提交意见反馈
        /// <returns>登录成功返回userinfo  -1异常 -4 参数错误</returns>
        public object SubmitFeedback([FromBody]PostFeedback post)
        {
            ModelBase mbase = new ModelBase();
            if (post.userId < 1 || StringUtils.IsNumeric(post.content))
            {
                mbase.code = -4;
                mbase.message = "参数错误";
                return mbase;
            }
            int _fresult = -1;
            _fresult = commdal.SaveOrUpdateSql("INSERT INTO [dbo].[yd_feedback] ([uid],[submitContent],[createrTime])VALUES(" + post.userId + ",'" + post.content + "',getdate())"); 
            if (_fresult == 0)
            {
                mbase.code = 0;
                mbase.message = "添加成功";
                return mbase;
            }
            mbase.code = _fresult;
            mbase.message = ErrorCodeUtil.getCodeMessage(_fresult);
            return mbase;
        }
    }
}
